package com.sxj.corejava.code02_jdbc;

import com.sxj.corejava.entity.User;

import java.sql.*;

/**
 * @author 石小俊
 * @date 2023年12月2023/12/2日 14:43
 */
public class Test09_事务操作 {

    public static void main(String[] args) throws SQLException {
        User user = new User("test2","123456","13612345678","江苏-南京");
        insertUser(user);
    }

    public static void insertUser(User user) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8","root","");

            // 开启事务
            conn.setAutoCommit(false);

            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setString(4,user.getAddress());
            ps.executeUpdate();

            int i = 1 / 0;

            // 提交事务
            conn.commit();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到驱动");
            // 回滚事务
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
            // 回滚事务
            conn.rollback();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("服务器内部异常");
            // 回滚事务
            conn.rollback();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("释放连接出错");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
